package pnu.ssm.ga;

import java.util.Iterator;

import pnu.ssm.controller.manager.JobManager;
import pnu.ssm.controller.manager.TransporterManager;
import pnu.ssm.model.job.Job;
import pnu.ssm.model.stuff.Transporter;

public class FitnessCalc {

	private static int maxFitness = 0;
	public static int tileDistance = 0;
	
	private static TransporterManager transporterMgr = TransporterManager.getInstance();
	private static JobManager jobMgr = JobManager.getInstance();

	public static double getMaxFitness() {
		return maxFitness;
	}

	public static int getFitness(Individual individual) {
		Transporter idleTransporter = null;
		for (int i = 0; i < individual.size(); i++) {
				idleTransporter = transporterMgr.getTransporter(individual.getGene(i));
				if (idleTransporter == null) break;
				Job allocJob = jobMgr.removeJob();
				if (allocJob == null) break;
				idleTransporter.allocateJob(allocJob);
				
				Iterator<Transporter> transporterIter = transporterMgr.iterator();
				while (transporterIter.hasNext()) {
					Transporter workingTransporter = transporterIter.next();
					workingTransporter.work();
				}
		}
		
		int totalEmptyDis = 0;
		Iterator<Transporter> it = transporterMgr.iterator();
		while(it.hasNext()){
			Transporter t = it.next();
			totalEmptyDis += t.getEmptyDis();
		}
		
		return totalEmptyDis;
	}
	
	public static int getFitnessByArr(int arr[]) {
		
		Transporter idleTransporter = null;
		for (int i = 0; i < arr.length; i++) {
				idleTransporter = transporterMgr.getTransporter(arr[i]);
				if (idleTransporter == null) break;
				Job allocJob = jobMgr.removeJob();
				if (allocJob == null) break;
				idleTransporter.allocateJob(allocJob);
				
				Iterator<Transporter> transporterIter = transporterMgr.iterator();
				while (transporterIter.hasNext()) {
					Transporter workingTransporter = transporterIter.next();
					workingTransporter.work();
				}
		}
		
		int totalEmptyDis = 0;
		Iterator<Transporter> it = transporterMgr.iterator();
		while(it.hasNext()){
			Transporter t = it.next();
			totalEmptyDis += t.getEmptyDis();
		}
		
		return totalEmptyDis;
	}
}

